
<template>
  <!-- 员工合同 -->
  <div>
    <el-row :gutter="24">
      <el-col :span="2">
        <div class="grid-content ep-bg-purple">
          <el-button type="primary" plain @click="add" style="width: 100px;">
            <el-icon><Plus /></el-icon>添加
          </el-button>
        </div>
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" plain style="border: none;">
          导入
          <i class="el-icon-upload el-icon--right"></i>
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" plain style="border: none;">
          导出
          <i class="el-icon-upload el-icon--right"></i>
        </el-button>
      </el-col>
      
      <el-col :span="2">
        <div class="grid-content ep-bg-purple">
          <el-button type="danger" plain @click="handleDelete">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </div>
      </el-col>
      
      <el-col :span="8">
        <div class="grid-content ep-bg-purple"></div>
      </el-col>
      
      <el-col :span="4">
        <div class="grid-content ep-bg-purple-light">
          <el-input style="width: 180px" size="large" placeholder="搜索">
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </div>
      </el-col>

      <el-col :span="1">
        <div class="grid-content ep-bg-purple-light">
          <a-tooltip content="筛选" position="bottom" background-color="rgb(52, 145, 250)" mini>
            <el-button size="default" @click="dialog = true">
              <el-icon><Filter /></el-icon>
            </el-button>
          </a-tooltip>
        </div>
      </el-col>

      <el-col :span="1">
        <div class="grid-content ep-bg-purple-light">
          <a-tooltip content="排序" position="bottom" background-color="rgb(52, 145, 250)" mini>
            <el-button size="default">
              <el-icon><Sort /></el-icon>
            </el-button>
          </a-tooltip>
        </div>
      </el-col>

      <el-col :span="2">
        <div class="grid-content ep-bg-purple-light">
          <a-tooltip content="刷新" position="bottom" background-color="rgb(52, 145, 250)" mini>
            <el-button size="default" @click="fetchEmployeeContracts">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </a-tooltip>
        </div>
      </el-col>
    </el-row>

    <el-table 
      :data="employeeContractsData" 
      border 
      style="width: 100%;" 
      @cell-dblclick="handleClick"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" fixed="left" label="选择" width="50" />
      <el-table-column v-for="col in columns" :prop="col.id" :key="col.id" :label="col.label" :width="col.width">
        <template #default="scoped">
          <el-button 
            v-if="col.id === 'mainContract' && scoped.row.mainContract === '是'"
            :style="{ backgroundColor: '#46C26F', borderColor: '#46C26F', color: '#FFFFFF' }" 
            disabled>
            {{ scoped.row.mainContract }}
          </el-button>
          <span v-else>{{ scoped.row[col.id] }}</span>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination 
      v-model:current-page="currentPage" 
      v-model:page-size="pageSize" 
      :page-sizes="[10, 20, 30, 40]"
      :disabled="disabled" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total" 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange">
    </el-pagination>

    <!-- 详情页面 -->
    <el-dialog title="详细信息" v-model="isVisible" fullscreen destroy-on-close @close="handleDialogClose">
      <hr />
      <DetailsOfTheTalent 
        ref="detailsRef" 
        @updated="onContractUpdated" 
        @close="handleDialogClose">
      </DetailsOfTheTalent>
    </el-dialog>
    
    <!-- 添加页面 -->
    <el-dialog title="添加合同" v-model="AddDisplay" fullscreen destroy-on-close @close="handleAddDialogClose">
      <OnboardingAddition @added="onContractAdded" @close="handleAddDialogClose"></OnboardingAddition>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%" center>
      <div style="text-align: center; padding: 20px 0;">
        <el-icon style="font-size: 40px; color: #F56C6C; margin-bottom: 10px;">
          <Warning />
        </el-icon>
        <p>确定要删除选中的 {{ selectedRows.length }} 条合同记录吗？</p>
        <p style="color: #999; font-size: 12px;">此操作不可恢复，请谨慎操作</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete" :loading="deleteLoading">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!--筛选-->
    <el-drawer v-model="dialog" title="筛选" direction="rtl" class="demo-drawer">
      <div class="demo-drawer__content">
        <el-form :model="form" style="height: 600px;">
          <el-select v-model="Screening" placeholder="筛选" style="width: 360px" placement="bottom">
            <template #label="{ label, value }">
              <span style="font-weight: bold">{{ label }}</span>
            </template>
            <el-option v-for="item in FilterData" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取消</el-button>
          <el-button type="primary" :loading="loading" @click="onClick">
            {{ loading ? '提交中 ...' : '提交' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'
import server from '@/api/request'
import { ElMessage } from 'element-plus'
import OnboardingAddition from '@/views/onboarding/employeeContracts/insert.vue'
import DetailsOfTheTalent from '@/views/onboarding/employeeContracts/detailed.vue'

const isVisible = ref(false) 
const AddDisplay = ref(false)
const loading = ref(false) 
const dialog = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const disabled = ref(false)
const total = ref(0)
const detailsRef = ref(null)
const currentContractId = ref(null)
const deleteDialogVisible = ref(false)
const deleteLoading = ref(false)

// 员工合同数据
const employeeContractsData = ref([])
const selectedRows = ref([])

const columns = ref([
  { id: 'employeeName', label: '员工成员', width: '200' },
  { id: 'dateOfInduction', label: '入职时间', width: '200' },               
  { id: 'workNumber', label: '工号', width: '120' },
  { id: 'department', label: '部门', width: '200' },
  { id: 'post', label: '岗位', width: '200' },
  { id: 'employeeStatus', label: '员工状态', width: '200' },
  { id: 'employmentForm', label: '聘用形式', width: '200' },
  { id: 'contractNumber', label: '合同编号', width: '200' },
  { id: 'mainContract', label: '主合同', width: '200' },
  { id: 'contractType', label: '合同类型', width: '200' },
  { id: 'contractStartDate', label: '合同开始日期', width: '200' },
  { id: 'contractEndDate', label: '合同结束日期', width: '200' },
  { id: 'contractDuration', label: '合同期限', width: '200' },
  { id: 'contractSubject', label: '合同主体', width: '200' },
  { id: 'contractRemarks', label: '合同备注', width: '200' }
])
const fetchEmployeeContracts = async () => {
  try {
    const response = await server.get('/employeeContracts/list', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })
    
    if (response.code === 200) {
      employeeContractsData.value = response.data.records
      total.value = response.data.total
    }
  } catch (error) {
    console.error('获取员工合同列表失败:', error)
    ElMessage.error('获取员工合同列表失败')
  }
}


// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}
const confirmDelete = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('没有选中的记录')
    return
  }
  
  deleteLoading.value = true
  
  try {
    const ids = selectedRows.value.map(row => row.contractsId)
    const response = await server.delete('/employeeContracts/delete', {
      data: { ids: ids }
    })
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      fetchEmployeeContracts()
    } else {
      ElMessage.error('删除失败: ' + response.message)
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  } finally {
    deleteLoading.value = false
  }
}
const form = ref()
const Screening = ref('') 
const FilterData = ref([ 
  { value: '全部', label: '全部' },
  { value: 'HR已确认', label: 'HR已确认' },
  { value: 'HR未确认', label: 'HR未确认' }
])
const fetchContractDetail = async (contractId) => {
  try {
    const response = await server.get(`/employeeContracts/detail/${contractId}`)
    if (response.code === 200) {
      if (detailsRef.value && typeof detailsRef.value.setContractDetail === 'function') {
        detailsRef.value.setContractDetail(response.data)
      }
    } else {
      ElMessage.error('获取合同详情失败: ' + response.message)
    }
  } catch (error) {
    console.error('获取合同详情失败:', error)
    ElMessage.error('获取合同详情失败')
  }
}
// 点击删除按钮进行删除
const handleDelete = () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }
  
  deleteDialogVisible.value = true
}

const handleClick = (row) => {
  console.log(row)
  currentContractId.value = row.contractsId
  isVisible.value = true
  nextTick(() => {
    fetchContractDetail(row.contractsId)
  })
}


const onClick = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    dialog.value = false
  }, 400)
}

const cancelForm = () => {
  loading.value = false
  dialog.value = false
}

// 打开添加对话框
const add = () => {
  AddDisplay.value = true
}

// 合同添加成功后的回调
const onContractAdded = () => {
  AddDisplay.value = false
  fetchEmployeeContracts()
}

// 处理添加对话框关闭
const handleAddDialogClose = () => {
  AddDisplay.value = false
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchEmployeeContracts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchEmployeeContracts()
}

// 合同更新后的回调
const onContractUpdated = () => {
  isVisible.value = false
  fetchEmployeeContracts()
}

// 处理对话框关闭
const handleDialogClose = () => {
  isVisible.value = false
}

// 页面加载时获取数据
onMounted(() => {
  fetchEmployeeContracts()
})
</script>

<style scoped></style>